<!--
  实验一
  商品展示网页
  类似于京东，淘宝
-->
<script setup lang="js">
import {computed, ref} from 'vue'
import hotSaleData from '../../resource/京东热卖.json'

const searchRef = ref('')
const data = hotSaleData

const filterRef=computed(()=>{
  return data.filter(v=>{
    return new RegExp(searchRef.value, 'i').test(v.name)
  })
})

const goToLink = (namelink) => {
  if (namelink) {
    window.open(namelink, '_blank')
  }
}

const splitPraise = (praiseText) => {
  const plusIndex = praiseText.indexOf('+')
  let numberIndex = 0

  for(let i = 0; i < praiseText.length; i++) {
    if (praiseText[i] >= '0' && praiseText[i] <= '9') {
      numberIndex = i
      break
    }
  }
  // 分割字符串
  const before = praiseText.substring(0, numberIndex)
  const number = praiseText.substring(numberIndex, plusIndex + 1)
  const rest = praiseText.substring(plusIndex + 1)

  return {before, number, rest }
}
</script>

<template>
  <q-banner class="bg-blue-grey-5 text-white">
    <p class="text-center text-h4 q-mt-md">陈一非 23211860123</p>
  </q-banner>
  <div class="row">
    <q-input v-model="searchRef" outlined standout="bg-teal text-white" label="搜索" maxlength="20" class="myinput">
      <template v-slot:before>
        <q-icon name="shopping_bag"/>
      </template>
      <template v-slot:append>
        <q-icon v-if="searchRef!==''" name="close"
        @click="searchRef=''" class="cursor-pointer" />
        <q-icon name="search"/>
      </template>
    </q-input>
  </div>

  <div class="row flex-center">
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 q-ma-sm"
        v-for="(item, index) in filterRef" :key="index" @click="goToLink(item.namelink)"
    >
      <q-card class="cursor-pointer full-height">
        <q-img :src="item.image" fit="cover" class="h-48 w-full" position="center center"/>

        <q-card-section >
          <div class="text-h6 text-red">
            {{ item.price }}
          </div>
          <p class="text-truncate">
            {{ item.name }}
          </p>
          <p class="text-caption">
            <span class="text-grey">{{ splitPraise(item.praise).before }}</span>
            <span class="text-blue-6">{{ splitPraise(item.praise).number }}</span>
            <span class="text-grey">{{ splitPraise(item.praise).rest }}</span>
          </p>
        </q-card-section>
      </q-card>
    </div>
  </div>
</template>

<style scoped>
.text-truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin: 10px 0;
}

.full-height {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.myinput {
  margin: 1px auto;
  width: 40%;
}
</style>
